package hw.ats.news.activity.news;

import hw.ats.news.R;
import hw.ats.news.activity.DBAwareActivity;
import hw.ats.news.model.Cate;
import hw.ats.news.model.News;
import hw.ats.news.ui.BottomTabHostProvider;
import hw.ats.news.ui.CateNavCallback;
import hw.ats.news.ui.CateNavHolder;
import hw.ats.news.ui.CommonUI;
import hw.ats.news.ui.NewsResourceHolder;
import hw.ats.news.util.App;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.humanwares.ui.asyncimage.ImageDisplayer;
import com.humanwares.ui.asyncimage.ImageReceivedCallback;
import com.humanwares.ui.asyncimage.ImageReceiver;
import com.humanwares.ui.tabbar.TabHost;
import com.tattermedia.allthataudio.misc.DebugFlag;

public class RecmdAct extends DBAwareActivity implements ImageReceivedCallback, CateNavCallback {
	private static final String TAG = "RecmdAct";
	
	private List<Cate> cates = null;
	private List<News> items = null;
	private List<News> headlines = null;
	private Gallery headlineView = null;
	private ListView listView = null;
	private DisplayMetrics dm = null;
	private TabHost navbar = null;
	
	private boolean thumbDisplay = false;
	
	// 현재 선택된 카테고리
	private Cate cate = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        thumbDisplay = pref.getBoolean("pref_list_thumb", true);
        
        // 데이터 로드
        initData();
        
        setContentView(R.layout.act_recmd);
        
        // 탭바 초기화
        navbar = CommonUI.renderTabBar(this, BottomTabHostProvider.TAB1);
        
		// 네이게이션바 제목
        CommonUI.renderAppTitle(this);
        
        // 좌측 네비게이션 버튼 = 검색화면이동
        CommonUI.addLeftNavigationButtonSearchEvent(this);
        
        // 우측 네비게이션 버튼 = All That 화면이동
        CommonUI.addRightNavigationButtonAllThatEvent(this);
        
        // 서브네비게이션바 생성
        CommonUI.makeWithCategorizedSubNavigation(this, cates, 0);
        
        // 헤드라인 출력
        showHeadline();

        // 추천글 출력
        showArt();
           
    }
    
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		if (DebugFlag.isLogEnabled()) Log.d(TAG, "onDestroy()");
		closeDatabase();
	}
    
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event)  {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//			new AlertDialog.Builder(RecmdAct.this)
//			.setTitle(App.APP_TITLE)
//			.setMessage(App.APP_TITLE+"을 종료하시겠습니까?")
//			.setPositiveButton(R.string.common_yes, new DialogInterface.OnClickListener() {
//			    public void onClick(final DialogInterface dialog, final int arg1) {
//			    	finish();
//			    }
//			})
//			.setNegativeButton(R.string.common_no, new DialogInterface.OnClickListener() {
//			    public void onClick(final DialogInterface dialog, final int arg1) {
//			    }
//			})
//			.show();
//			
//            return true;
//        }
//
//        return super.onKeyDown(keyCode, event);
//    }
    
    /**
     * 이미지 로더
     */
    @Override
	public void onImageReceived(ImageDisplayer displayer) {
		this.runOnUiThread(displayer);
	}
	
    /**
     * 메뉴 보기/숨기기
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        int visibility = navbar.getVisibility();
        navbar.setVisibility(visibility == View.VISIBLE ? View.INVISIBLE : View.VISIBLE);
        return false;
    }
    
    /**
     * 카테고리바 선택
     */
	@Override
	public void onSelectCateNav(int position, CateNavHolder holder) {
		if (DebugFlag.isLogEnabled()) 
			Log.d(TAG, "position="+position);
		
		Cate cate = holder.select(position);
		
		if (DebugFlag.isLogEnabled()) 
			Log.d(TAG, "cate="+cate.title);
		
		// 카테고리 선택시 최신글로 연결
		HorizontalScrollView sv = (HorizontalScrollView)findViewById(R.id.navcat_scroll);
		int scrollX = sv.getScrollX();
		Intent intent = new Intent(this, RecentAct.class);
		intent.putExtra(App.INTENT_EXTRA_CATE_UID, cate.uid);
		intent.putExtra(App.INTENT_EXTRA_SCROLL_X, scrollX);
		startActivity(intent);
		
		/* 요청으로 막아둠
		// 헤드라인
		headlines = News.listRecmd(getReadableDatabase(), cate.uid, 0, 5);
		
		// 글
		items = News.listRecmd(getReadableDatabase(), cate.uid, 5, 25);

		((BaseAdapter)headlineView.getAdapter()).notifyDataSetChanged();
		((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
		
		headlineView.setSelection(0);
		
		TextView titleView = (TextView)findViewById(R.id.topbar_title);
		titleView.setText("추천글 > " + cate.title);
		
        final ScrollView sv = (ScrollView)findViewById(R.id.scrollbar);
        sv.post(new Runnable() {
			@Override
			public void run() {
				sv.scrollTo(0, 0);
				sv.postInvalidate();
			}
		});
		*/
	}
    
	/**
	 * 헤드라인 목록
	 */
	private void showHeadline() {
        headlineView = (Gallery)findViewById(R.id.headline_pane);
        headlineView.setAdapter(new HeadlineAdapter(this));
        headlineView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				News news = headlines.get(position);
				Intent intent = new Intent(RecmdAct.this, ViewAct.class);
				intent.putExtra(App.INTENT_EXTRA_NEWS_UID, news.uid);
				intent.putExtra(App.INTENT_EXTRA_ACT_NAME, RecmdAct.class.getName());
			    startActivity(intent);
			}
		});
        
        ImageButton btnPrev = (ImageButton)findViewById(R.id.headline_prev);
        btnPrev.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int pos = headlineView.getSelectedItemPosition();
				if (pos == 0) return;
				headlineView.setSelection(pos-1);
			}
		});
        
        ImageButton btnNext = (ImageButton)findViewById(R.id.headline_next);
        btnNext.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int pos = headlineView.getSelectedItemPosition();
				if (pos >= headlineView.getCount() - 1) return;
				headlineView.setSelection(pos+1);
			}
		});	
	}
	
	/**
	 * 추천글 목록
	 */
	private void showArt() {
        listView = (ListView)findViewById(R.id.recmd_list);
        listView.setAdapter(new RecmdAdapter(this));
        
        // ListView 높이를 컨텐츠에 맞게 자동 조정
        float h = 66.0f;
        float r = items.size();
        
        float scale = getResources().getDisplayMetrics().density;
        //Log.d(TAG, "scale="+scale);
        int height = (int) (h * r * scale + r - 1.0f + 0.5f);
        // dip높이 * 개수 * 배율(1.5) + 개수 - 1 + 0.5
        // -----------------------   --------
        // 셀의 합산                   구분선
        
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)listView.getLayoutParams();
		params.height = height;
		listView.setLayoutParams(params);
		//////////////////////////////////////
        
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				News news = items.get(position);			
				Intent intent = new Intent(RecmdAct.this, ViewAct.class);
				intent.putExtra(App.INTENT_EXTRA_NEWS_UID, news.uid);
				intent.putExtra(App.INTENT_EXTRA_CATE_UID, cate != null ? cate.uid : 0);
				intent.putExtra(App.INTENT_EXTRA_ACT_NAME, RecmdAct.class.getName());
			    startActivity(intent);
			}
        });
        
        final ScrollView sv = (ScrollView)findViewById(R.id.scrollbar);
        sv.post(new Runnable() {
			@Override
			public void run() {
				sv.scrollTo(0, 0);
				sv.postInvalidate();
			}
		});
	}
	
	/**
	 * 추천글 목록 데이터 어뎁터
	 * @author pcraft
	 */
    private class RecmdAdapter extends BaseAdapter {
    	private final static String TAG = "RecmdAdapter";
    	private final Activity context;

        public RecmdAdapter(Activity context) {
        	this.context = context;
        }

        public int getCount() {
        	if (items == null)
        		return 0;
        	
            return items.size();
        }

        public Object getItem(int position) {
            return items.get(position);
        }

        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            NewsResourceHolder holder = null;
            if (view == null) {
            	LayoutInflater vi = context.getLayoutInflater();
            	if (thumbDisplay)
            		view = vi.inflate(R.layout.row_news_type2, null);
            	else
            		view = vi.inflate(R.layout.row_news_type1, null);
                holder = new NewsResourceHolder(view);
                view.setTag(holder);
            } else {
            	holder = (NewsResourceHolder)view.getTag();
            }
            
            News entry = items.get(position);
    		if (entry == null) {
    			return view;
    		}

            if (DebugFlag.isLogEnabled())
            	Log.d(TAG,
            		"pos="+position+
            		" img="+holder.imageView+
            		" cv="+convertView+
            		" par="+parent);
    		
            if (holder.imageView != null) {
            	holder.imageView.setTag(position);
            	holder.imageView.setImageBitmap(null);
                new ImageReceiver(entry.thumb_default, (ImageReceivedCallback)context, 
                		holder.imageView, getThumbPath(), position);
            }
            
            if (holder.titleView != null)
            	holder.titleView.setText(entry.title);
            
            if (holder.detailView != null) {
            int len = entry.body_text.length();
            	if (len > 256) len = 256;
            	holder.detailView.setText(entry.body_text.substring(0, len));
            }
    		
    		return view;
        }
    }
    
    /**
     * 헤드라인 데이터 어뎁터
     * @author pcraft
     */
	private class HeadlineAdapter extends BaseAdapter {
		private Activity context = null;
		
		public HeadlineAdapter(Activity context) {   
			this.context = context;
        }
		
		@Override
		public int getCount() {
			if (headlines == null)
				return 0;
			
			return headlines.size();
		}

		@Override
		public Object getItem(int position) {
			return headlines.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            NewsResourceHolder holder = null;
            
            News news = headlines.get(position);
            final TextView headlineTitleView = (TextView)RecmdAct.this.findViewById(R.id.headline_title);
            headlineTitleView.setText(news.title);
            
            if (view == null) {
            	LayoutInflater vi = context.getLayoutInflater();
            	view = vi.inflate(R.layout.row_recmd_headline, null);
                holder = new NewsResourceHolder(view);
                view.setTag(holder);
            } else {
            	holder = (NewsResourceHolder)view.getTag();
            }
            
            if (holder.imageView != null) {
            	holder.imageView.setTag(position);
            	holder.imageView.setImageResource(App.RES_LOADING_480x265);
            	
				new ImageReceiver(news.main_image, (ImageReceivedCallback)context, 
	            		holder.imageView, getThumbPath(), position);
            }
            
			return view;
		}
	}
	
	/**
	 * 출력할 데이터 초기 로딩
	 */
	private void initData() {
		// 카테고리
    	cates = Cate.list(getReadableDatabase());

    	cate = null;
		int catId = getIntent().getIntExtra(App.INTENT_EXTRA_CATE_UID, 0);
		if (catId > 0) {
			for (Cate c : cates) {
				if (c.uid == catId) {
					cate = c;
					break;
				}
			}
		}
		
    	// 헤드라인
		headlines = News.listRecmd(getReadableDatabase(), 0, 3); // change from 5 to 3
		
		// 글
		items = News.listRecmd(getReadableDatabase(), 3, 25); //change from 5 to 3
	}
}
